package net.sahv.bdyz.controller.admin;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sahv.bdyz.model.Admin;
import net.sahv.bdyz.model.AdminLoginInfo;
import net.sahv.bdyz.service.AdminLoginInfoService;
import net.sahv.bdyz.util.IPUtil;
import net.sahv.bdyz.util.Security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping("admin/login")
public class LoginController {
	
	@Autowired
	private AdminLoginInfoService adminLoginInfoService;
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(Admin admin,RedirectAttributes redirectAttributes,Model model,String vcode,HttpServletRequest request){
		String validateCode=(String) request.getSession().getAttribute("validateCode");
		
		if(vcode.trim().equalsIgnoreCase(validateCode)){
			Subject currentUser = SecurityUtils.getSubject();
			Security security=new Security();
			String passwordSecurity=security.encryptAES(admin.getaPassword(),Security.generateAesKey("sahv"));
			admin.setaPassword(passwordSecurity);
			UsernamePasswordToken token = new UsernamePasswordToken(admin.getaUsername(),admin.getaPassword());
			
			try {
				  
				//使用权限工具进行用户登录，登录成功后跳到shiro配置的successUrl中，与下面的return没什么关系！ 
				
				  System.out.println("对用户[" + admin.getaUsername() + "]进行登录验证..验证开始");  
		            currentUser.login(token);  
		            System.out.println("对用户[" + admin.getaUsername() + "]进行登录验证..验证通过");  
		        }catch(UnknownAccountException uae){  
		            System.out.println("对用户[" + admin.getaUsername() + "]进行登录验证..验证未通过,未知账户");  
		            redirectAttributes.addFlashAttribute("message", "未知账户");  
		            return "redirect:/admin/admin/login";
		        }catch(IncorrectCredentialsException ice){  
		            System.out.println("对用户[" + admin.getaUsername() + "]进行登录验证..验证未通过,错误的凭证");  
		            redirectAttributes.addFlashAttribute("message", "密码不正确");  
		            return "redirect:/admin/admin/login";
		        }catch(LockedAccountException lae){  
		            System.out.println("对用户[" + admin.getaUsername() + "]进行登录验证..验证未通过,账户已锁定");  
		            redirectAttributes.addFlashAttribute("message", "账户已锁定");  
		            return "redirect:/admin/admin/login";
		        }catch(ExcessiveAttemptsException eae){  
		            System.out.println("对用户[" + admin.getaUsername() + "]进行登录验证..验证未通过,错误次数过多");  
		            redirectAttributes.addFlashAttribute("message", "用户名或密码错误次数过多");  
		            return "redirect:/admin/admin/login";
		        }catch(AuthenticationException ae){  
		            //通过处理Shiro的运行时AuthenticationException就可以控制用户登录失败或密码错误时的情景  
		            System.out.println("对用户[" + admin.getaUsername() + "]进行登录验证..验证未通过,堆栈轨迹如下");  
		           
		            redirectAttributes.addFlashAttribute("message", "用户名或密码不正确");  
		            return "redirect:/admin/admin/login";
		        }  
				
			 //验证是否登录成功  
	        if(currentUser.isAuthenticated()){  
	            System.out.println("用户[" + admin.getaUsername() + "]登录认证通过(这里可以进行一些认证通过后的一些系统参数初始化操作)"); 
	            //记录后台用户的登陆信息
	            HttpSession session=request.getSession();
	            Admin adminSession=(Admin) session.getAttribute("currentUser");
	            AdminLoginInfo adminLoginInfo=new AdminLoginInfo();
	            adminLoginInfo.setaId(adminSession.getaId());
	            adminLoginInfo.setAliTime(new Date());
	            //获取登陆人的IP地址：
	            String ipString=IPUtil.getClientIP(request);
	            adminLoginInfo.setAliClient(ipString);
	            adminLoginInfo.setAliIsDelete(0);
	            adminLoginInfoService.insert(adminLoginInfo);
	            //查询登陆信息，按降序排列
	            List<AdminLoginInfo> listAll=adminLoginInfoService.selectAllOrderByLoginTimeDesc();
	            //将上次登陆信息存放到session中
	            session.setAttribute("adminLoginInfo", listAll.get(1));
	        }else{  
	            token.clear();
	        } 
	        return "redirect:/admin/welcome/index";
		}else{
			redirectAttributes.addFlashAttribute("message", "验证码不正确！");
			return "redirect:/admin/admin/login";
		}
        
    }
		
	/**
	 * 退出操作系统
	 * @author 张天敏
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/logout",method=RequestMethod.GET)  
    public String logout(RedirectAttributes redirectAttributes ){ 
		//使用权限管理工具进行用户的退出，跳出登录，给出提示信息
        SecurityUtils.getSubject().logout();  
        redirectAttributes.addFlashAttribute("message", "您已安全退出");  
        return "redirect:/admin/admin/login";
    } 
	
	@RequestMapping("/403")
	public String unauthorizedRole(){
		return "/403";
	}
}